

import os
import pickle
import datetime
import zlib
import xmlrpclib

class FileStorage( object ):

    def __init__( self ):

        print "FileStorage initializing"

        self._storeLocation = self._storeLocation or ""

    def storeFile( self, name, info, xmlrpcBinary ):
        """
        """

        storeInfoName = os.path.join( self._storeLocation, '%s.info' % name ) # pylint: disable-msg=W0212
        storeContName = os.path.join( self._storeLocation, '%s.cont' % name ) # pylint: disable-msg=W0212

        info = { "crc" : zlib.crc32( xmlrpcBinary.data ),
                 "timestamp" : datetime.datetime.now(),
                 "info" : info, }

        try:
            with open( storeInfoName, 'wb' ) as output:
                pickle.dump( info, output )

            with open( storeContName, 'wb' ) as output:
                output.write( zlib.compress( xmlrpcBinary.data ) )

            return True

        except IOError:
            if os.path.exists( storeInfoName ):
                os.remove( storeInfoName )

            if os.path.exists( storeContName ):
                os.remove( storeContName )

                return False

        return False

    def retrieveFile( self, name ):
        """
        """

        storeInfoName = os.path.join( self._storeLocation, '%s.info' % name ) # pylint: disable-msg=W0212
        storeContName = os.path.join( self._storeLocation, '%s.cont' % name ) # pylint: disable-msg=W0212

        try:
            with open( storeInfoName, 'rb' ) as infoFile:
                info = pickle.load( infoFile )

            with open( storeContName, 'rb' ) as contFile:
                content = zlib.decompress( contFile.read() )

            return info['info'], xmlrpclib.Binary(content)

        except ( IOError, zlib.error ):
            return None, None
